<template>
  <div class="app-container">
    <!-- <t-Search /> -->
    <el-form :model="param" ref="publishRef" :rules="publishRules" label-width="0">
      <el-card class="form_card">
        <span class="_before">基本信息</span>
          <div>
            <div class="main-list">
               <div class="main-list-item">
                 <div class="main-list-item-label">
                 <span style="color: red;">* </span>
                   提箱城市
                </div>
                 <div class="main-list-item-value">
                  <el-select :disabled="typeRef==2" v-model="from.carryCityName" @change="carryCityIdChang" filterable clearable style="width: 240px" placeholder="请选择提箱城市">
                        <el-option
                            v-for="item in cityList"
                            :key="item.id"
                            :label="item.cityCName"
                            :value="{ value: item.id, label: item.cityCName}"                                                      
                        />
                      </el-select>  
                        <!-- <el-select-v2
                          v-model="from.carryCityId"
                          :options="cityList"
                          :props="{ value: 'id', label: 'cityCName' }"
                          placeholder="请选择提箱城市"
                          filterable                           
                          style="width: 300px"
                        /> -->
                </div>
              </div>
               <div class="main-list-item">
                 <div class="main-list-item-label">
                 <span style="color: red;">* </span>
                   还箱城市
                </div>
                 <div class="main-list-item-value">
                  <el-select :disabled="typeRef==2" v-model="from.returnCity" multiple filterable clearable collapse-tags  collapse-tags-tooltip style="width: 240px" placeholder="请选择还箱城市">
                        <el-option
                            v-for="item in cityList"
                            :key="item.id"
                            :label="item.cityCName"
                            :value="{ value: item.id, label: item.cityCName}"       
                        />
                      </el-select>
                </div>
              </div>
            </div>       
           <div class="main-list">
              <div class="main-list-item">
                 <div class="main-list-item-label">
                  <span style="color: red;">* </span>
                    箱使期
                </div>
                 <div class="main-list-item-value">
                     <el-input :disabled="typeRef==2" v-model.trim="from.boxUsagePeriod" style="width: 240px" placeholder="请输入箱使期" maxlength="5" >
                  <template #append>天</template>
                </el-input>
                </div>
              </div>
           </div>
             <div class="main-list">
              <div class="main-list-item">
                 <div class="main-list-item-label">
                  <span style="color: red;">* </span>
                    超期费:
                </div>
                 <div class="main-list-item-value" style="display: flex;align-items: center;">
                    超期1天后，$
                      <el-input :disabled="typeRef==2" v-model.trim="from.overdueFeeDay" :min="0" style="width: 80px" />
                    &nbsp; 箱/天；
                     超期 &nbsp;
                    <el-input :disabled="typeRef==2" v-model.trim="from.lossDay" :min="0" style="width: 80px" />
                    &nbsp;天后，仍未还箱，视为灭失，灭失费为
                    &nbsp;$&nbsp;
                    <el-input :disabled="typeRef==2" v-model.trim="from.lossFee" :min="0" style="width: 80px" />
                </div>
              </div>
              <div class="main-list-item">
                 <div class="main-list-item-label">
                    修箱费:
                </div>
                 <div class="main-list-item-value">还箱时，实报实销</div>
              </div>
           </div>
             <div class="main-list">
              <div class="main-list-item">
                 <div class="main-list-item-label">            
                    货品名称
                </div>
                 <div class="main-list-item-value">                    
                  <el-input v-model.trim="from.cargoName" :disabled="typeRef==2" style="width: 240px" placeholder="请输入货品名称" maxlength="100" />
                </div>
              </div>
           </div>   
           <div class="main-list">
              <div class="main-list-item">
                 <div class="main-list-item-label">发布人:</div>
                 <div class="main-list-item-value">{{ from.publisherName }}</div>
                  <div class="main-list-item-label"><span style="color: red;">* </span>可结算币种</div>
                 <div class="main-list-item-value">
                    <el-checkbox-group v-model="from.payCurrency" :disabled="typeRef==2">
                        <el-checkbox label="人民币" value="CNY" />
                        <el-checkbox label="美元" value="USD" />
                    </el-checkbox-group>
                </div>
              </div>
              <div class="main-list-item">
                 <div class="main-list-item-label"><span style="color: red;">* </span>结算流向</div>
                 <div class="main-list-item-value">
                     <el-radio-group v-model="from.direction" :disabled="typeRef==2">
                        <el-radio :value="1">应收</el-radio>
                        <el-radio :value="-1">应付</el-radio>
                      </el-radio-group>
                </div>
            </div> 
            </div> 
            <div class="main-list">
              <div class="main-list-item">
                <div class="main-list-item-label" style="text-align: left;"><span style="color: red;">* </span>规格</div>             
              </div> 
            </div>
            <div class="table">
              <div class="table-top">
                <div class="table-title">箱型</div>
                <div class="table-title">箱况</div>
                <div class="table-title">箱标</div>
                <div class="table-title">币种</div>
                <div class="table-title">单价</div>
              </div>
              <div class="tatle-for" v-for="(item, index) in from.releaseRentPriceList" :key="index">
                <div class="tatle-list">
                  <el-icon v-if="typeRef==1" style="margin-right: 15px;" color="#2158F3" @click="removeGui(index)"><RemoveFilled /></el-icon>
                   <el-select v-model="item.boxType" style="width: 80%" :disabled="typeRef==2" placeholder="请选择箱型">
                        <el-option
                            v-for="item in dictList.boxTypeInfo"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                      </el-select>
                </div>
                  <div class="tatle-list">
                   <el-select v-model="item.boxCondition" :disabled="typeRef==2" style="width: 80%" placeholder="请选择箱况">
                        <el-option
                            v-for="item in dictList.boxConditionInfo"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                      </el-select>
                </div>
                  <div class="tatle-list">                 
                      <el-select v-model="item.totalWeight" :disabled="typeRef==2" style="width: 80%">
                        <el-option label="32500KG" value="32500KG" />
                        <el-option label="30480KG " value="30480KG" />
                        <el-option label="30480/32500KG" value="30480/32500KG" />
                      </el-select>
                </div>
                  <div class="tatle-list">
                    <el-select v-model="item.currency" :disabled="typeRef==2" style="width: 80%">
                        <el-option label="人民币(CNY)" value="CNY" />
                        <el-option label="美元(USD)" value="USD" />
                      </el-select>
                </div>
                  <div class="tatle-list">
                     <el-input v-model="item.unitPrice" :disabled="typeRef==2" placeholder="请输入单价" style="width: 80%" maxlength="5" >
                        <template #prepend>{{item.currency=='CNY' ? '￥':'$' }}</template>
                      </el-input>
                </div>
              </div>
              <div class="tatle-list" v-if="typeRef==1">
                  <el-icon style="margin-right: 15px;" color="#2158F3"><CirclePlusFilled /></el-icon>
                  <span style="display: inline-block;width: 80%;text-align: left;color: #2158F3;" @click="addGui">新增规格</span>
              </div>
            </div>
        </div>
      </el-card>
       <el-card class="form_card" style="margin-top: 15px;">
        <span class="_before">图文描述</span>
        <div class="main-data">
            <div class="mst-bis"><span style="color: red;">* </span>主图</div>
            <div style="width:100%">
              <div class="div-box-dark">
                <upload-Img ref="uploadImgRef" :urlList="param.showMainImgList" @uploadSccess="uploadMainSccess"
                  @uploadRemoveSccess="uploadRemoveMainImgSccess" :disabledUpload="typeRef==2" style="width:1000px;height: 1000px;" />
                <div style="margin-top: 5px;color: #999;">请上传 png/jpg 主图，大小不能超过3M，建议图片像素高于700*700px</div>
              </div>
            </div>
             <div class="mst-bis">详情描述</div>
              <div style="width: 100%;">
              <ImageTextEditor ref="editor" :previewHtml="detailFileList" :isDisabled="typeRef==2"></ImageTextEditor>
              </div>
          </div>
       
        </el-card>
     <el-affix v-if="typeRef==1" position="bottom" class="marginTop20">
        <el-card>
           <el-row align="middle" justify="center">
            <div v-if="param.isLoading" style="margin:auto;color: chocolate;">数据提交中......</div>
            <div v-else style="margin:auto;">
              <el-button @click="onSave('save')">保存待发布</el-button>
              <el-button type="primary" plain @click="onSave('putWarehouse')">放入仓库</el-button>
              <el-button type="primary" @click="onSave('publish')">立即发布</el-button>
            </div>
          </el-row>
        </el-card>
      </el-affix>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance, onActivated, onMounted, reactive, ref, watch } from 'vue';
import uploadImg from '@/components/upload/img.vue'
import {getBoxInfo,saveBox,publishBox ,boxEastInWarehouse} from '@/api/boxRent/indexNew.ts'
import ImageTextEditor from '@/components/upload/imageTextEditor'
import dictList from '@/utils/dictList'
import { useRoute, useRouter } from 'vue-router';
import { ElMessage,ElMessageBox } from 'element-plus';
import Cookies from "js-cookie";
const router = useRouter();
const route = useRoute();
const editor = ref()
const detailFileList = ref()
const typeRef=ref(1) //1编辑 2查看

const from=ref({
  id:null,
  carryCityId:'',
  carryCityName:'',
  returnCity:[],
  boxUsagePeriod:60,
  direction:1,//结算流向 1-收入 -1-支出
  overdueFeeDay:10,//超期一天的费用 /箱/天
  overdueFeeCurrency:'USD',//超期费币种 CNY:人民币 USD:美元 默认美元
  lossDay:70,//灭失天数
  lossFee:7000,//灭失费
  cargoName:'',
  publisherId:'',
  publisherName:'',
  payCurrency:['CNY'],//结算币种(美元:USD 人民币:CNY 用英文逗号分割)
  mainFileList:[],//主图
  releaseRentPriceList:[{
    boxType:5,
    boxCondition:5,
    unitPrice:"",
    currency:"CNY",
    totalWeight:"32500KG",
  }],//规格List
  detailFileList:'',//详情信息

})
let param = reactive({
  showMainImgList:[],
})

const cityList=ref([])//全部城市
onActivated(() => {
  let userInfo = JSON.parse(Cookies.get("User-Info"))
  cityList.value = JSON.parse(localStorage.getItem('cityList'))
  from.value.publisherName=userInfo.nickname
  from.value.publisherId=userInfo.id
  showData()
})

//添加规格
const addGui=()=>{
  let obj={
        boxType:5,
        boxCondition:5,
        unitPrice:"",
        currency:"CNY",
        totalWeight:"32500KG",
  }
  from.value.releaseRentPriceList.push(obj)
}
//移除规格
const removeGui=(index)=>{
  if(from.value.releaseRentPriceList.length==1){
      ElMessage.warning("至少保留一条规格数据");
      return false
    }else{
      from.value.releaseRentPriceList.splice(index, 1)
    }
}

//出发城市
const carryCityIdChang=(val)=>{
  if(val){
    from.value.carryCityId=val.value
    from.value.carryCityName=val.label
  }else{
    from.value.carryCityId=''
    from.value.carryCityName=''
  }

}
const showData = async () => {
  let id=route.query.id
   if(route.query.type){
    typeRef.value=route.query.type

  }
  if (id) {

    await getBoxInfo(id).then(async (res: any) => {
      let data = res.data
      from.value=data
      param.showMainImgList = JSON.parse(data.mainFileList)
      let returnCity=JSON.parse(data.returnCity)
      let returnCityList=[]
      returnCity.forEach((item)=>{
          let obj={
            value:item.returnCityId,
            label: item.returnCityName,
          }
          returnCityList.push(obj)
        })
      from.value.returnCity=returnCityList
      from.value.payCurrency=data.payCurrency.split(',')
      editor.value.setData(data.detailFileList)
    })
  }
}

// //清空数据
// const clearData = () => {
//   optId.value = null
//   param.boxBackCity = []
//   backCityList.value = []
//   param.marks = [{ textVal: '', imgInfo: [] }]
//   param.loading = false
//   param.boxSizeHistory = {}// eg={40HQ:[{ size: string; info: any; price: string; num: string; }],20HQ:[],40GP:[],200GP:[]} 
//   param.totalWeight = 1
//   param.period = ''
//   param.overdueFeeDay = 10
//   param.lossDay = 10
//   param.lossFee = 10
//   param.boxUsagePeriod = 60
//   param.period = 15
//   param.showMainImgList = []
//   param.historyList = []
// }


// 城市排序
const sortCity = (cityArry: any) => {
  // 使用 reduce 方法将相同 id 的城市分组
  const grouped = cityArry.reduce((acc, city) => {
    if (!acc[city.startCityId]) {
      acc[city.startCityId] = [];
    }
    acc[city.startCityId].push(city);
    return acc;
  }, {});
  // 将分组的城市展平为一个数组
  const sortedArray = Object.values(grouped).flat();
  return sortedArray;
}

//上传成功的（主图上传）
const uploadMainSccess = (data: any) => {
  param.showMainImgList.push(data)
}
//img删除成功(主图删除)
const uploadRemoveMainImgSccess = (data: any) => {
  let index = param.showMainImgList.findIndex((item: any) => {
    return item.uid == data.uid
  })
  if (index != -1) {
    param.showMainImgList.splice(index, 1)
  }
}


// 提交
const uploadImgRef = ref()
const onSave = async (opr: any) => {
  const queryStr = route.query.type;
  let isReturn=false
  let template= JSON.parse(JSON.stringify(from.value))
  if (template.carryCityId=='') {
      ElMessage.warning('提箱城市不能为空');
      return false
  }else if(template.returnCity.length==0){
       ElMessage.warning('还箱城市不能为空');
      return false
  }else if(template.boxUsagePeriod==''){
       ElMessage.warning('箱使期不能为空');
      return false
  }else if(template.overdueFeeDay==''){
       ElMessage.warning('超期1天后费用不能为空');
      return false
  }else if(template.lossDay==''){
       ElMessage.warning('超期天数不能为空');
      return false
  }else if(template.lossFee==''){
       ElMessage.warning('灭失费不能为空');
      return false
  }else if(template.payCurrency.length==0){
       ElMessage.warning('结算币种不能为空');
      return false
  }else if(param.showMainImgList.length==0){
       ElMessage.warning('主图不能为空');
      return false
  }
   template.releaseRentPriceList.forEach((item)=>{
    if (!item.unitPrice) {
      ElMessage.warning('规格单价不能为空');
       isReturn=true
      return
    }
  })
  if(isReturn){
    return false
  }
  let returnCity=[]
template.returnCity.forEach((item)=>{
    let obj={
        returnCityId: item.value,
        returnCityName: item.label,
    }
    returnCity.push(obj)
  })
  template.returnCity=JSON.stringify(returnCity)
  template.payCurrency=template.payCurrency.join(',')
  template.mainFileList=JSON.stringify(param.showMainImgList)
   template.detailFileList=editor.value.getContent()
  if (opr == 'save') {
      param.isLoading = true
      await saveBox(template).then((res: any) => {
        param.isLoading = false
        router.back()
      }).catch((err: any) => {
        setTimeout(() => {
          param.isLoading = false
        }, 2000)
      })  
  }
  if(opr == 'putWarehouse'){
    param.isLoading = true
    await boxEastInWarehouse(template).then((res: any) => {
      param.isLoading = false
      router.back()
    }).catch((err: any) => {
      setTimeout(() => {
        param.isLoading = false
      }, 2000)
    })
  }
  if (opr == 'publish') {
    param.isLoading = true
     await publishBox(template).then((res: any) => {
      param.isLoading = false
      router.back()
    }).catch((err: any) => {
      setTimeout(() => {
        param.isLoading = false
      }, 2000)
    })
  }
}


//校验
const validateMainImgList = (rule: any, value: any, callback: any) => {
  if (value) {
    const length = value.length
    if (length < 1) {
      callback(new Error('不能为空'))
    } else {
      callback()
    }
  } else {
    callback(new Error('不能为空'))
  }
}
const publishRules = {
  boxBackCity: [{ required: true, trigger: "change", message: "不能为空" }],
  boxStartCity: [{ required: true, trigger: "change", message: "不能为空" }],
  period: [
    { required: true, trigger: "blur", message: "不能为空" },
  ],
  overdueFeeDay: [
    { required: true, trigger: "blur", message: "不能为空" },
  ],
  lossFee: [
    { required: true, trigger: "blur", message: "不能为空" },
  ],
  lossDay: [
    { required: true, trigger: "blur", message: "不能为空" },
  ],
  boxUsagePeriod: [
    { required: true, trigger: "blur", message: "不能为空" },
  ],
  mainImgList: [
    { required: true, validator: validateMainImgList, trigger: 'blur' },
  ],
}


</script>

<style scoped>
.tagCard {
  background-color: WhiteSmoke;
  border: 1px solid #DCDCDC;
  border-size: border-box;
  padding: 10px;
  border-radius: 5px;
  margin-right: 5px
}

.main-list{
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-top:15px ;
}
.main-list-item{
  display: flex;
  align-items: center;
}
.main-list-item-label{
  margin-right: 10px;
  width: 120px;
  text-align: right;
}
.table{
  width: 100%;
  margin-top:20px ;
}
.table-top{
  display: flex;
  padding: 10px 0;
background: #f8f8f8;
}
.table-title{
  width: 20%;
  text-align: center;
}
.tatle-for{
  display: flex;
}
.tatle-list{
  width: 20%;
  text-align: center;
  margin-top:15px ;
}
.main-data{
  margin-top: 20px;
}
.mark-list{
  display: flex;
  margin-top: 20px;
}
.main-data-fl{
  width: 50%;
}
.main-data-fr{
  width: 50%;
  position: relative;
}
.pos{
  position: absolute;
  right: 0;
  top: -0;
  width: 10px;
  height: 10px;
}
.mst-bis{
  margin: 10px 0;
}
</style>